package com.monster.servlet.user;

import com.alibaba.fastjson.JSON;
import com.monster.pojo.User;
import com.monster.service.UserService;
import com.monster.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;

@WebServlet("/user/code_reg_check")
public class CodeRegisterCheckServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String code = request.getParameter("code");
        UserService us = new UserServiceImpl();
        String message = "验证码已超时，请重新发送";
        HashMap<String, Date> maps = null;
        if ((maps = (HashMap<String, Date>)session.getAttribute("smsCode")) != null) {
            for (String smsCode : maps.keySet()) {
                Date then = maps.get(smsCode);
                Date now = new Date();
                if ((now.getTime() - then.getTime()) <= 5 * 1000 * 60 && smsCode.equals(code)) {
                    String password = request.getParameter("password");
                    String phoneNumber = (String) session.getAttribute("code_phone");
                    User user = new User();
                    user.setName("用户"+code);
                    user.setPassword(password);
                    user.setPhoneNumber(phoneNumber);
                    user.setHead("images/user/a0.png");
                    us.register(user);
                    message = "register success";
                } else if (!smsCode.equals(code)) {
                    message = "验证码错误";
                }
            }
        }
        PrintWriter out = response.getWriter();
        out.print(message);
        out.flush();
        out.close();

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
